package com.atguigu.tingshu.live.config;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.live.SocketMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
public class RedisListenConfig {
    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public RedisMessageListenerContainer messageListenerContainer(RedisConnectionFactory connectionFactory) {
        //初始化一个监听者容器,可以放多个监听器
        RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
        //设置连接工厂,监控连接
        listenerContainer.setConnectionFactory(connectionFactory);
        //向容器中添加监听器
        listenerContainer.addMessageListener((message, pattern) -> {
            //获取对应的序列化器,进行反序列化
            SocketMsg msg = (SocketMsg)this.redisTemplate.getValueSerializer().deserialize(message.getBody());
            //通过中介者转发消息
            LiveRoomContainer.sendMsg(msg);
        },new ChannelTopic(RedisConstant.LIVE_MESSAGE_CHANNEL));

        return listenerContainer;
    }
}
